<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="perm" uri="/WEB-INF/tld/perm.tld"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<script>var ctx="${ctx}";</script>

<html>
	<head>
	    <meta charset="utf-8">
	    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	    <title>商品管理</title>
	    <meta name="keywords" content="体验,友好,高级管理台,易用,高性能,高扩展性,bootstrap框架,响应式后台">
	    <meta name="description" content="这是一个完全响应式，基于Bootstrap3最新版本开发的扁平化主题，她采用了主流的左右两栏式布局，使用了Html5+CSS3等现代技术">
	    <meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="Cache-Control" content="no-cache, must-revalidate">
		<meta http-equiv="expires" content="Wed, 26 Feb 209908:21:57 GMT"> 
	    
		<link rel="shortcut icon" href="favicon.ico"> 
		<link href="${ctx}/static/css/bootstrap.min.css?v=${static_version}/" rel="stylesheet">
		<link href="${ctx}/static/css/font-awesome.min.css?v=4.4.0?v=${static_version}/" rel="stylesheet">
		<link href="${ctx}/static/css/plugins/footable/footable.core.css?v=${static_version}/" rel="stylesheet">
		<link href="${ctx}/static/css/plugins/summernote/summernote.css?v=${static_version}/" rel="stylesheet">
		<link href="${ctx}/static/css/plugins/summernote/summernote-bs3.css?v=${static_version}/" rel="stylesheet">
		<link href="${ctx}/static/plugins/laypage/laypage.css?v=${static_version}"  rel="stylesheet">
		<link href="${ctx}/static/css/plugins/iCheck/custom.css?v=${static_version}/" rel="stylesheet">
		<link href="${ctx}/static/css/plugins/chosen/chosen.css?v=${static_version}/" rel="stylesheet">
		<link href="${ctx}/static/css/animate.min.css?v=${static_version}/" rel="stylesheet">
		<link href="${ctx}/static/js/plugins/layer/laydate/laydate.css?v=${static_version}/" rel="stylesheet">
		<link href="${ctx}/static/css/plugins/webuploader/webuploader.css?v=${static_version}/" rel="stylesheet">
		<link href="${ctx}/static/css/style.min.css?v=${static_version}/" rel="stylesheet">
		<link href="${ctx}/static/css/plugins/switchery/switchery.css?v=${static_version}/" rel="stylesheet">
		<link href="${ctx}/static/js/plugins/uploadify/uploadify.css?v=${static_version}/" rel="stylesheet">
	    
	</head>
	<body class="gray-bg">
	
	<input type="hidden" name="token" id="token" value="<%=request.getSession().getAttribute("token") %>" />
	
	<div class="wrapper wrapper-content animated fadeInRight">
		<div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>分类/品牌 </h5>
                        <div class="ibox-tools">
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <form method="get" class="form-horizontal">
                        	<div class="form-group">
						 	    <label class="col-md-2 col-sm-2 control-label">分类:</label>
						        <div class="col-md-9">
						        	 <select id="catId" data-placeholder="选择商品分类" class="chosen-select full-width"  tabindex="4">
									</select>
						        </div>
						    </div>
							<div class="form-group">
						 	    <label class="col-md-2 col-sm-2 control-label">品牌:</label>
						        <div class="col-md-9">
						        	  <select id="brandId" data-placeholder="选择商品分类" class="chosen-select full-width"  tabindex="4">
									</select>
						        </div>
						    </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>基本信息 </h5>
                        <div class="ibox-tools">
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <form method="get" class="form-horizontal">
                            <div class="form-group">
						 	    <label class="col-md-2 col-sm-2 control-label">名称:</label>
						        <div class="col-md-9">
						        	 <input id="name" value="${goods.name}" data-check="require:true;code:^[a-zA-Z0-9\u4e00-\u9fa5]{2,20};message:必输输入 2-20位中文、数字或字母"  type="text" data-check="require:true;code:^[a-zA-Z0-9\u4e00-\u9fa5]{2,20};message:必输输入 2-20位中文、数字或字母"  type="text" placeholder="名称" class="form-control" name="name"/>
						        </div>
						    </div>
							<div class="form-group">
						 	    <label class="col-md-2 col-sm-2 control-label">编号:</label>
						        <div class="col-md-9">
						        	 <input id="sn" value="${goods.sn}" data-check="require:true;code:^[a-zA-Z0-9]{2,26};message:必输输入 2-20位数字或字母"  type="text" data-check="require:true;code:^[a-zA-Z0-9\u4e00-\u9fa5]{2,20};message:必输输入 2-20位中文、数字或字母"  type="text" placeholder="编号" class="form-control" name="sn"/>
						        </div>
						    </div>
						    <div class="form-group">
						 	    <label class="col-md-2 col-sm-2 control-label">市场价:</label>
						        <div class="col-md-9">
						        	 <input id="price" value="${goods.price}"  type="text" placeholder="市场价" class="form-control" name="price"/>
						        </div>
						    </div>
						    <div class="form-group">
						 	    <label class="col-md-2 col-sm-2 control-label">发货地:</label>
						        <div class="col-md-9">
						        	 <input id="shipAddr" value="${goods.shipAddr}"  type="text" placeholder="发货地" class="form-control" name="shipAddr"/>
						        </div>
						    </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>商品规格 </h5>
                        <div class="ibox-tools">
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <form method="get" class="form-horizontal">
                        	<div class="form-group">
						 	    <label class="col-md-2 col-sm-2 control-label">开启规格:</label>
						        <div class="col-md-9">
						        	 	<input type="checkbox" class="js-switch" name="have_spec" <c:if test="${goods.haveSpec==1}">checked</c:if> />
						        </div>
						    </div>
						    <div class="well m-t" style="padding-left: 0">
						    	<div class="form-group">
						 	    	<label class="col-md-2 col-sm-2 control-label">封面图片:</label>
							        <div class="col-md-9">
							        	 <div class="col-md-10" style="padding-left: 0;">
								        	 <input class="fileInput" id="faceUploadify" type="file" name="file" multiple="multiple" accept="image/*"/>
								        	 <div class="faceUploadify">
								        	 	<c:if test="${not empty(goods.face) }">
								        	 	<img src="${goods.face }" style="width: 60px;height: 60px;margin-right:5px;">
								        	 	</c:if>
											 </div>
								       </div>
							        </div>
							     </div>
							     <div class="form-group">
								 	    <label class="col-md-2 col-sm-2 control-label">商品相册:</label>
								        <div class="col-md-9">
								        	 <div class="col-md-10" style="padding-left: 0;">
									        	 <input class="fileInput" id="galleryUploadify" type="file" name="file" multiple="multiple" accept="image/*"/>
									        	 <div class="galleryUploadify"> 
									        	 	<c:if test="${not empty(goods.gallery) }">
									        	 	<c:forEach items="${fn:split(goods.gallery,',') }" var="g">
									        	 	<img src="${g }" style="width: 60px;height: 60px;margin-right:5px;">
									        	 	</c:forEach>
									        	 	</c:if>
												 </div>
									        </div> 
								        </div>
								    </div>
						    	<div id="no_spec" <c:if test="${goods.haveSpec==0}">style="display:none;"</c:if>>
									<div class="form-group" >
					 	    			<label class="col-md-2 col-sm-2 control-label">特卖价:</label>
								        <div class="col-md-9">
								        	 <input id="sale_price" type="text" placeholder="特卖价" class="form-control" name="sale_price" value="${goods.salePrice }"/>
								        </div>
								    </div>
								    <div class="form-group" >
					 	    			<label class="col-md-2 col-sm-2 control-label">库存:</label>
								        <div class="col-md-9">
								        	 <input id="stock" type="text" placeholder="库存" class="form-control" name="stock" value="${productEntitys[0].stock }"/>
								        </div>
								    </div>
						    	</div>
						    	<div id="ha_spec" <c:if test="${goods.haveSpec==1}">style="display:block;"</c:if>>
								     <div id="specDiv"></div>
								     <div id="createTable" style="margin: 0 auto;width: 95%;"></div>
						    	</div>
						    </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>商品属性 </h5>
                        <div class="ibox-tools">
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <form method="get" class="form-horizontal">
                        	<div id="paramsdiv">
                        		<c:choose>
                        			<c:when test="${empty(params) }">
                        			<div class="form-group">
									  	<div class="col-md-2">
								        	 <input id="name" type="text" placeholder="属性名" class="form-control" name="param_value"/>
								        </div>
								        <div class="col-md-8">
								        	 <input id="name" type="text" placeholder="属性值" class="form-control" name="param_value"/>
								        </div>
								        <div class="col-md-2">
								        	 <button  type="button" class="btn btn-outline btn-primary" onclick="addParam()">增加</button>
								        </div>
							    	</div>
                        			</c:when>
                        			<c:otherwise>
                        			<c:forEach items="${params }" var="p" varStatus="index">
	                        		<div class="form-group">
									  	<div class="col-md-2">
								        	 <input id="name" type="text" placeholder="属性名" class="form-control" name="param_value" value="${p.name }"/>
								        </div>
								        <div class="col-md-8">
								        	 <input id="name" type="text" placeholder="属性值" class="form-control" name="param_value" value="${p.value }"/>
								        </div>
								        <div class="col-md-2">
								        	 <button  type="button" class="btn btn-outline btn-primary" onclick="addParam()">增加</button>
								        	 <c:if test="${index.index!=0 }">
								        	 <button  type="button" class="btn btn-outline btn-danger" onclick="delParam(this)">删除</button>
								        	 </c:if>
								        </div>
							    	</div>
	                        		</c:forEach>
                        			</c:otherwise>
                        		</c:choose>
                        	</div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>商品介绍 </h5>
                        <div class="ibox-tools">
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <form method="get" class="form-horizontal">
					        <div class="form-group">
						 	    <label class="col-md-2 col-sm-2 control-label">介绍:</label>
						        <div class="col-md-9">
						        	 <script type="text/plain" id="editor">${goods.intro}</script>
						        </div>
						    </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="form-group">
             <div class="col-sm-4 col-sm-offset-4" style="text-align: center;">
                 <button class="btn btn-primary" type="button" onclick="addGoods()">保存</button>
                 <button class="btn btn-white" type="button" onclick="updateClose()">取消</button>
             </div>
         </div>
    </div>
	
	
	
	<script src="${ctx}/static/js/jquery.min.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/bootstrap.min.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/footable/footable.all.min.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/validate/jquery.validate.min.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/validate/messages_zh.min.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/webuploader/webuploader.min.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/summernote/summernote.min.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/summernote/summernote-zh-CN.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/chosen/chosen.jquery.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/layer/laydate/laydate.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/iCheck/icheck.min.js?v=${static_version}"></script>
	<script src="${ctx}/static/plugins/laypage/laypage.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/switchery/switchery.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/eModal.min.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/cookie.js?v=?v=${static_version}"></script>
	<script src="${ctx}/static/common/custom-datatable.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/content.min.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/contabs.min.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/ueditor-1.4.3/ueditor.config.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/ueditor-1.4.3/ueditor.all.js?v=${static_version}"></script>
	<script src="${ctx}/static/common/common.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/layer/layer.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/plugins/uploadify/jquery.uploadify.js?v=${static_version}"></script>
	<script src="${ctx}/static/js/jquery.form.js?v=${static_version}"></script>
	
	</body>
</html>
<script>

var updateClose=function(me){
	window.location.href=ctx+"/goods/index";
}

$(function(){
	jQuery.checkall(false);
})
var step;
//初始化规格
specChange($("[name='have_spec']"));
$("[name='have_spec']").change(function(){
	specChange($(this));
})
$("#catId").change(function(){
	specChange($("[name='have_spec']"));
})
function specChange(o,stype){
	if(o.is(":checked")){
		layer.load(2);
		var scatid=$("#catId").val();
		if(scatid==null)scatid="${goods.catId}";
		$.ajax({ url: "${ctx}/goodsCat/findSpecs?catid="+scatid,async:false , success: function(data){
			if(data.code==0){
				$("#no_spec").hide();$("#ha_spec").show();
				$("#specDiv").html("");
				$.getJSON("${ctx}/spec/specAll?specs="+data.data,function(data){
					var specHtml="";
					for(var i=0;i<data.length;i++){
					specHtml+="<div class=\"form-group\">"+
 						"<label class=\"col-md-2 col-sm-2 control-label Father_Title\" value=\""+data[i].id+"\">"+data[i].name+":</label>"+
						"<div class=\"col-md-9 Father_Item"+i+"\">";
							for(var j=0;j<data[i].childs.length;j++){
								specHtml+="<label class=\"checkbox-inline i-checks\"><input type=\"checkbox\" ";
								if("${goodsSpec}".indexOf(data[i].childs[j].id)>-1){
									specHtml+="checked";
								}
								specHtml+=" data-specids=\""+data[i].id+"|"+data[i].childs[j].id+"|"+data[i].name+"|"+data[i].childs[j].name+"\" value=\""+data[i].childs[j].name+"\">"+data[i].childs[j].name+"</label>";
							}
						specHtml+="</div></div>";
					}
					$("#specDiv").html(specHtml);
					$("#createTable").html("");
					$(".i-checks").iCheck({checkboxClass:"icheckbox_square-green"});
					icheckSpecInit();
					step.Creat_Table();
					layer.closeAll('loading');
				})
			}else{
				o.click();
				layer.closeAll('loading');
			}
	    }});
	}else{
		$("#ha_spec").hide();$("#no_spec").show();
	}
}
//添加商品
function addGoods(){
		if (!jQuery.checkall(true)) return;
	var data;
	var products=[];
	var goodsParams=[];
	var gallerys=[];
	var have_spec=$("[name='have_spec']").is(":checked")?1:0;
	$("#paramsdiv .form-group").each(function(){
		var paramName=$(this).find("input:first").val();
		var paramValue=$(this).find("input:last").val();
		if(($.trim(paramValue)!="")&&($.trim(paramName)!="")){
			goodsParams.push({name:paramName,value:paramValue});
		}
	})
	$(".galleryUploadify img").each(function(){
		gallerys.push($(this).attr("src"));
	})
	if(have_spec==0){
		if(${goods.haveSpec}==0){
			products.push({id:'${productEntitys[0].id}',sn:$("#sn").val(),salePrice:$("#sale_price").val(),gallery:gallerys.toString(),face:$(".faceUploadify img").attr("src"),stock:$("#stock").val()});
		}else{
			products.push({sn:$("#sn").val(),salePrice:$("#sale_price").val(),gallery:gallerys.toString(),face:$(".faceUploadify img").attr("src"),stock:$("#stock").val()});
		}
		data={
				catId:$("#catId").val(),
				brandId:$("#brandId").val(),
				name:$("#name").val(),							
				sn:$("#sn").val(),							
				price:$("#price").val(),
				salePrice:$("#sale_price").val(),
				haveSpec:have_spec,
				goodsParams:goodsParams,							
				intro:ue.getContent(),									
				face:$(".faceUploadify img").attr("src"),
				shipAddr:$("#shipAddr").val(),
				gallery:gallerys.toString(),
				products:products,
				id:"${goods.id}",
				token:$("#token").val()
		    } ;
	}else{
		var minPrice=0.0;
		$("#createTable tbody tr").each(function(i){
			var specsIds="";
			var face=$(this).find("#face"+i+" img").attr("src");
			var specDescript="";
			var gallery="";
			var sale_price=$(this).find("[name='sale_price']").val();
			$(this).find("[type='hidden']").each(function(){
				specsIds+="|"+$(this).val();
				specDescript+=";"+$(this).attr("specValue");
			})
			$(this).find("[id^='gallery']").find("img").each(function(){
				gallery+=","+$(this).attr("src");
			})
			if(i==0)minPrice=sale_price;
			if(sale_price<minPrice)minPrice=sale_price;
			products.push({id:$(this).attr("id"),sn:$(this).find("[name='sn']").val(),salePrice:sale_price,stock:$(this).find("[name='stock']").val(),face:face,gallery:gallery.substring(1),specsIds:specsIds.substring(1),specs:specDescript.substring(1)});
		})
		data={
				catId:$("#catId").val(),
				brandId:$("#brandId").val(),
				name:$("#name").val(),							
				sn:$("#sn").val(),							
				price:$("#price").val(),
				salePrice:minPrice,
				haveSpec:have_spec,
				goodsParams:goodsParams,							
				intro:ue.getContent(),									
				face:$(".faceUploadify img").attr("src"),
				shipAddr:$("#shipAddr").val(),
				gallery:gallerys.toString(),
				products:products,
				id:"${goods.id}",
				token:$("#token").val()
		    } ;
	}
	$.ajax({
	    type: 'POST',
	    url: ctx+"/goods/update",
	    data: JSON.stringify(data),
	    dataType: "json",
	    contentType:"application/json",
	    success:function(data){
	    	if(data.code==0){
	    		window.location.href=ctx+"/goods/index";
	    	}else {
				alert("修改失败");
	    	}
	    }
	});
}
function delParam(obj){
    $(obj).parents(".form-group").remove();           
}

function addParam(){
	$("#paramsdiv").append("<div class=\"form-group\">"+
		  	"<div class=\"col-md-2\">"+
				 "<input type=\"text\" placeholder=\"属性名\" class=\"form-control\" name=\"param_name\"/>"+
			"</div>"+
			"<div class=\"col-md-8\">"+
				 "<input type=\"text\" placeholder=\"属性值\" class=\"form-control\" name=\"param_value\"/>"+
			"</div>"+
			"<div class=\"col-md-2\">"+
				 "<button  type=\"button\" class=\"btn btn-outline btn-primary\" onclick=\"addParam()\">增加</button>"+
				 "<button  type=\"button\" class=\"btn btn-outline btn-danger\" onclick=\"delParam(this)\">删除</button>"+
			"</div>"+
			"</div>");
}
$(function(){
	$("#catId").chosen({ width: '100%' });
	$("#brandId").chosen({ width: '100%' });
    $.ajax({  
		url:'${ctx}/goodsCat/list',  		 					
		type: 'POST',
		dataType:'json',  
		success:function(response){
			if(response.code==0){
				var html=[];
				var data=response.data||[];
				for(var i=0;i<data.length;i++){
					html.push('<option value="'+data[i].id+'">'+data[i].name+'</option>');
				}
				$("#catId").append(html.join(""));
				$("#catId").val("${goods.catId}");
				$("#catId").trigger("chosen:updated");
			}
		 }  
     });
    
    $.ajax({  
		url:'${ctx}/brand/list',  		 					
		type: 'POST',
		dataType:'json',  
		success:function(response){
			if(response.code==0){
				var html=[];
				var data=response.data||[];
				for(var i=0;i<data.length;i++){
					html.push('<option value="'+data[i].id+'">'+data[i].name+'</option>');
				}
				$("#brandId").append(html.join(""));
				$("#brandId").val("${goods.brandId}");
				$("#brandId").trigger("chosen:updated");
			}
		 }  
     });
}); 	
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function(html) {
	var switchery = new Switchery(html);
}); 



/**
 * Ueditor初始化
 */
UE.delEditor("editor");
var ue=UE.getEditor('editor',{
    //这里可以选择自己需要的工具按钮名称,此处仅选择如下五个
    toolbars: [[
	   'fullscreen', 'source', '|', 'undo', 'redo', '|',
       'bold', 'italic', 'underline', 'fontborder', 'removeformat', 'formatmatch', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist',
       'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
       'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
       'indent',
       'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
       'link', 'unlink','simpleupload', 'insertimage','insertvideo'
	 ]],
     //关闭字数统计
     wordCount:false,
     initialFrameHeight:300,
     //关闭elementPath
     elementPathEnabled:false
})


$("#galleryUploadify").uploadify({
	'buttonImage':'${ctx}/static/js/plugins/uploadify/uploadify-button.png',
    'swf': '${ctx}/static/js/plugins/uploadify/uploadify.swf',
    'uploader':'${ctx}/file/uploadOss',
    'onFallback' : function() {//检测FLASH失败调用 
    	alert("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");  
    },  
    'onUploadSuccess':function(file, data, response){
    	var jData = jQuery.parseJSON(data);
        $(".galleryUploadify").append("<img src=\""+jData.data+"\" style=\"width: 60px;height: 60px;margin-right:5px;\">");
	}
});

$("#faceUploadify").uploadify({
	'buttonImage':'${ctx}/static/js/plugins/uploadify/uploadify-button.png',
    'swf': '${ctx}/static/js/plugins/uploadify/uploadify.swf',
    'uploader':'${ctx}/file/uploadOss',
    "multi":false,
    'onFallback' : function() {//检测FLASH失败调用 
    	alert("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");  
    },  
    'onUploadSuccess':function(file, data, response){
    	var jData = jQuery.parseJSON(data);
        $(".faceUploadify").html("<img src=\""+jData.data+"\" style=\"width: 60px;height: 60px;margin-right:5px;\">");
	}
});
function initProductUploadify(){
	$("[id^='specFaceUploadify']").each(function(index){
		$("[id='specFaceUploadify"+index+"']").uploadify({
			'buttonImage':'${ctx}/static/js/plugins/uploadify/uploadify-button.png',
		    'swf': '${ctx}/static/js/plugins/uploadify/uploadify.swf',
		    'uploader':'${ctx}/file/uploadOss',
		    "multi":false,
		    'onFallback' : function() {//检测FLASH失败调用 
		    	alert("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");  
		    },  
		    'onUploadSuccess':function(file, data, response){
		    	var jData = jQuery.parseJSON(data);
		    	$("#face"+index).html("<img src=\""+jData.data+"\" style=\"width: 40px;height: 40px;margin-right:3px;\">");
			}
		});
	})
	$("[id^='specGalleryUploadify']").each(function(index){
		$("[id='specGalleryUploadify"+index+"']").uploadify({
			'buttonImage':'${ctx}/static/js/plugins/uploadify/uploadify-button.png',
		    'swf': '${ctx}/static/js/plugins/uploadify/uploadify.swf',
		    'uploader':'${ctx}/file/uploadOss',
		    "multi":true,
		    'onFallback' : function() {//检测FLASH失败调用 
		    	alert("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");  
		    },  
		    'onUploadSuccess':function(file, data, response){
		    	var jData = jQuery.parseJSON(data);
		    	$("#gallery"+index).append("<img src=\""+jData.data+"\" style=\"width: 40px;height: 40px;margin-right:3px;\">");
			}
		});
	})
}

function icheckSpecInit(){
	$(".well [type='checkbox']").on('ifChecked ifUnchecked', function(event){
	  step.Creat_Table();
	});
	
	//SKU信息
	step = {
	  //SKU信息组合
	  Creat_Table: function () {
	      step.hebingFunction();
	      var SKUObj = $(".Father_Title");
	      var arrayTile = new Array();//标题组数
	      var arrayInfor = new Array();//盛放每组选中的CheckBox值的对象
	      var arrayColumn = new Array();//指定列，用来合并哪些列
	      var bCheck = true;//是否全选
	      var columnIndex = 0;
	      $.each(SKUObj, function (i, item){
	          arrayColumn.push(columnIndex);
	          columnIndex++;
	          arrayTile.push(SKUObj.eq(i).html().replace(":", ""));
	          var itemName = "Father_Item" + i;
	          //选中的CHeckBox取值
	          var order = new Array();
	          $("." + itemName + " input[type=checkbox]").each(function (){
	          	if($(this).is(":checked")){
	          		order.push($(this).data("specids")+"|"+$(this).val());
	          	}
	          });
	          arrayInfor.push(order);
	          if (order.join() == ""){
	              bCheck = false;
	          }
	      });
	      //开始创建Table表
	      if (bCheck == true) {
	          var RowsCount = 0;
	          $("#createTable").html("");
	          var table = $("<table class=\"table invoice-table\" style=\"border:solid 1px #e7eaec;\"></table>");
	          table.appendTo($("#createTable"));
	          var thead = $("<thead></thead>");
	          thead.appendTo(table);
	          var trHead = $("<tr></tr>");
	          trHead.appendTo(thead);
	          //创建表头
	          $.each(arrayTile, function (index, item) {
	              var td = $("<th style=\"border:solid 1px #e7eaec;\">" + item + "</th>");
	              td.appendTo(trHead);
	          });
	          var itemColumHead = $("<th style=\"border:solid 1px #e7eaec;\">货号</th><th style=\"border:solid 1px #e7eaec;\">特卖价</th><th style=\"border:solid 1px #e7eaec;\">库存</th><th style=\"border:solid 1px #e7eaec;\">封面</th><th style=\"border:solid 1px #e7eaec;\">相册</th> ");
	          itemColumHead.appendTo(trHead);
	          var tbody = $("<tbody></tbody>");
	          tbody.appendTo(table);
	          ////生成组合
	          var zuheDate = step.doExchange(arrayInfor);
	          if (zuheDate.length > 0) {
	              //创建行
	              $.each(zuheDate, function (index, item) {
	                  var td_array = item.split(",");
	                  var tr = $("<tr></tr>");
	                  tr.appendTo(tbody);
	                  $.each(td_array, function (i, values) {
	                      var td = $("<td style=\"border:solid 1px #e7eaec;\"><input class=\"form-control\" type=\"hidden\" value=\""+values.split("|")[0]+","+values.split("|")[1]+"\" specValue=\""+values.split("|")[2]+":"+values.split("|")[3]+"\">" + values.split("|")[4] + "</td>");
	                      td.appendTo(tr);
	                  });
	                  var td1 = $("<td style=\"border:solid 1px #e7eaec;\"><input class=\"form-control\" name=\"sn\" type=\"text\" placeholder=\"货号\"></td>");
	                  td1.appendTo(tr);
	                  var td2 = $("<td style=\"border:solid 1px #e7eaec;\"><input class=\"form-control\" name=\"sale_price\" type=\"text\" placeholder=\"特卖价\"></td>");
	                  td2.appendTo(tr);
	                  var td3 = $("<td style=\"border:solid 1px #e7eaec;\"><input class=\"form-control\" name=\"stock\" type=\"text\" placeholder=\"库存\"></td>");
	                  td3.appendTo(tr);
	                  var td4 = $("<td style=\"border:solid 1px #e7eaec;\"><input class=\"fileInput\" id=\"specFaceUploadify"+index+"\" type=\"file\" name=\"file\" multiple=\"multiple\" accept=\"image/*\"/><div id=\"face"+index+"\"></div></td>");
	                  td4.appendTo(tr);
	                  var td5 = $("<td style=\"border:solid 1px #e7eaec;\"><input class=\"fileInput\" id=\"specGalleryUploadify"+index+"\" type=\"file\" name=\"file\" multiple=\"multiple\" accept=\"image/*\"/><div id=\"gallery"+index+"\"></div></td>");
	                  td5.appendTo(tr);
	              });
	          }
	          //结束创建Table表
	          arrayColumn.pop();//删除数组中最后一项
	          //合并单元格
	          $(table).mergeCell({
	              // 目前只有cols这么一个配置项, 用数组表示列的索引,从0开始
	              cols: arrayColumn
	          });
	          initProductUploadify();
	          //初始化数据
	          initTableData();
	      } else{
	          //未全选中,清除表格
	          document.getElementById('createTable').innerHTML="";
	      }
	  },//合并行
	  hebingFunction: function () {
	      $.fn.mergeCell = function (options) {
	          return this.each(function () {
	              var cols = options.cols;
	              for (var i = cols.length - 1; cols[i] != undefined; i--) {
	                  // fixbug console调试
	                  // console.debug(cols[i]);
	                  mergeCell($(this), cols[i]);
	              }
	              dispose($(this));
	          });
	      };
	      function mergeCell($table, colIndex) {
	          $table.data('col-content', ''); // 存放单元格内容
	          $table.data('col-rowspan', 1); // 存放计算的rowspan值 默认为1
	          $table.data('col-td', $()); // 存放发现的第一个与前一行比较结果不同td(jQuery封装过的), 默认一个"空"的jquery对象
	          $table.data('trNum', $('tbody tr', $table).length); // 要处理表格的总行数, 用于最后一行做特殊处理时进行判断之用
	          // 进行"扫面"处理 关键是定位col-td, 和其对应的rowspan
	          $('tbody tr', $table).each(function (index) {
	              // td:eq中的colIndex即列索引
	              var $td = $('td:eq(' + colIndex + ')', this);
	              // 取出单元格的当前内容
	              var currentContent = $td.html();
	              // 第一次时走此分支
	              if ($table.data('col-content') == '') {
	                  $table.data('col-content', currentContent);
	                  $table.data('col-td', $td);
	              } else {
	                  // 上一行与当前行内容相同
	                  if ($table.data('col-content') == currentContent) {
	                      // 上一行与当前行内容相同则col-rowspan累加, 保存新值
	                      var rowspan = $table.data('col-rowspan') + 1;
	                      $table.data('col-rowspan', rowspan);
	                      // 值得注意的是 如果用了$td.remove()就会对其他列的处理造成影响
	                      $td.hide();
	                      // 最后一行的情况比较特殊一点
	                      // 比如最后2行 td中的内容是一样的, 那么到最后一行就应该把此时的col-td里保存的td设置rowspan
	                      if (++index == $table.data('trNum'))
	                          $table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
	                  } else { // 上一行与当前行内容不同
	                      // col-rowspan默认为1, 如果统计出的col-rowspan没有变化, 不处理
	                      if ($table.data('col-rowspan') != 1) {
	                          $table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
	                      }
	                      // 保存第一次出现不同内容的td, 和其内容, 重置col-rowspan
	                      $table.data('col-td', $td);
	                      $table.data('col-content', $td.html());
	                      $table.data('col-rowspan', 1);
	                  }
	              }
	          });
	      }
	      // 同样是个private函数 清理内存之用
	      function dispose($table) {
	          $table.removeData();
	      }
	  },
	  //组合数组
	  doExchange: function (doubleArrays) {
	      var len = doubleArrays.length;
	      if (len >= 2) {
	          var arr1 = doubleArrays[0];
	          var arr2 = doubleArrays[1];
	          var len1 = doubleArrays[0].length;
	          var len2 = doubleArrays[1].length;
	          var newlen = len1 * len2;
	          var temp = new Array(newlen);
	          var index = 0;
	          for (var i = 0; i < len1; i++) {
	              for (var j = 0; j < len2; j++) {
	                  temp[index] = arr1[i] + "," + arr2[j];
	                  index++;
	              }
	          }
	          var newArray = new Array(len - 1);
	          newArray[0] = temp;
	          if (len > 2) {
	              var _count = 1;
	              for (var i = 2; i < len; i++) {
	                  newArray[_count] = doubleArrays[i];
	                  _count++;
	              }
	          }
	          return step.doExchange(newArray);
	      }
	      else {
	          return doubleArrays[0];
	      }
	  }
	}
}

function initTableData(){
	var products = jQuery.parseJSON('${products}');
	$("#createTable tbody tr").each(function(index){
		var cur=$(this);
		for(var i=0;i<products.length;i++){
			var flag=true;
			var specsIds=products[i].specsIds;
			if(specsIds==null)return false;
			for(var j=0;j<cur.find("[type='hidden']").length;j++){
				if(specsIds.indexOf(cur.find("[type='hidden']").eq(j).val().split(',')[1])<0){
					flag=false;
				}
			}
			if(flag){
				cur.attr("id",products[i].id);
				cur.find("[name='sn']").val(products[i].sn);
				cur.find("[name='sale_price']").val(products[i].salePrice);
				cur.find("[name='stock']").val(products[i].stock);
				if(products[i].face!=null&&products[i].face!=''){
					cur.find("#face"+index).html("<img src=\""+products[i].face+"\" style=\"width: 40px;height: 40px;margin-right:3px;\">");
				}
				if(products[i].gallery!=null&&products[i].gallery!=''){
					var imgs=products[i].gallery.split(',');
					for(var k=0;k<imgs.length;k++)
						cur.find("#gallery"+index).append("<img src=\""+imgs[k]+"\" style=\"width: 40px;height: 40px;margin-right:3px;\">");
				}
			}
		}
	})
}
</script>